#pragma once

#include <iostream>
#include <string>
#include <functional>
#include <pthread.h>
#include <stdint.h>

namespace ThreadModule
{
    // 原⼦计数器，⽅便形成线程名称
    uint32_t cnt = 0;

    using threadfunc_t = std::function<void()>;
    // 线程状态
    enum class TSTATUS
    {
        THREAD_NEW,
        THREAD_RUNNING,
        THREAD_STOP
    };
    // 线程
    class Thread
    {
    private:
        static void *run(void *obj)//传编号
        {
            Thread *self = static_cast<Thread *>(obj);//static_cast 强转
            pthread_setname_np(pthread_self(), self->_name.c_str()); // 设置线程名称
            self->_status = TSTATUS::THREAD_RUNNING;//状态变为run
            if (!self->_joined)//并没有等待
            {
                pthread_detach(pthread_self());//分离
            }
            self->_func();//执行方法
            return nullptr;
        }
        void SetName()
        {
            // 后期加锁保护
            _name = "Thread-" + std::to_string(cnt++);
        }

    public:
        Thread(threadfunc_t func) : 
            _status(TSTATUS::THREAD_NEW),
            _joined(true), _func(func)
        {
            SetName();
        }
        void EnableDetach()
        {
            if (_status == TSTATUS::THREAD_NEW)
                _joined = false;
        }
        void EnableJoined()
        {
            if (_status == TSTATUS::THREAD_NEW)
                _joined = true;
        }
        bool Start()
        {
            if (_status == TSTATUS::THREAD_RUNNING)
                return true;
            int n = ::pthread_create(&_id, nullptr, run, this);
            if (n != 0)
                return false;
            return true;
        }
        bool Join()
        {
            if (_joined)
            {
                int n = pthread_join(_id, nullptr);
                if (n != 0)
                    return false;
                return true;
            }
            return false;
        }
        ~Thread() {}

    private:
        std::string _name;
        pthread_t _id;
        TSTATUS _status;
        bool _joined;
        threadfunc_t _func;
    };
}
